package com.kd.controller;

import com.kd.common.*;

import com.kd.dao.CustomerMapper;
import com.kd.entity.Customer;


import com.kd.service.customer.CustomerService;
import com.kd.service.email.EmailCodeService;
import com.kd.service.token.CustomerTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@RestController
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    CustomerService customerService;
    @Autowired
    CustomerTokenService tokenService;
    @Autowired
    EmailCodeService emailCodeService;

    @RequestMapping("/login")
    @ResponseBody
    public Result<Customer> login(@RequestBody Customer loginer, HttpServletRequest request) {
        // 调试1：打印前端提交的原始密码
        System.out.println(" 前端提交的密码: " + loginer.getPassword());

        Customer storeCustomer = customerService.findCustomerByPhone(loginer.getPhone());
        if (storeCustomer == null) {
            return Result.fail(" 用户不存在");
        }

//        String ip = getIp(request);  //获取ip
        // 调试3：手动验证密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isMatch = encoder.matches(loginer.getPassword(),  storeCustomer.getPassword());



        if (isMatch) {
            String token = tokenService.getToken(storeCustomer);
            return Result.success(storeCustomer,  "登录成功", token);
        } else {
            return Result.fail(" 账号或密码错误");
        }
    }



    /*@RequestMapping("/register")
    public Result.RegisterResult<Integer> register(@RequestBody Customer customer,HttpServletRequest request) {

        // 1. 参数基础校验
        if (customer.getPhone()  == null || customer.getPhone().trim().isEmpty())  {
            return Result.RegisterResult.fail(" 手机号不能为空");
        }

        // 2. 查重验证
        Integer existMid = customerService.getCidByphone(customer.getPhone());
        if (existMid != null && existMid != 0) {
            return Result.RegisterResult.<Integer>fail("注册失败，已注册的工号：" + existMid)
                    .data(existMid);
        }

        // 3. 执行注册
        try {
            customer.setIp(ipUtils.getIp(request));
            customer.setRegister_date(new Date());
            boolean success = customerService.insert(customer);
            if (success) {
                customer.setCid(customerService.getCidByphone(customer.getPhone()));
                return Result.RegisterResult.success(customer.getCid())
                        .message("注册成功"); // 使用链式调用设置消息
            }
            return Result.RegisterResult.fail(" 系统繁忙，注册失败");
        } catch (Exception e) {
            return Result.RegisterResult.fail(" 注册异常：" + e.getMessage());
        }
    }*/

    @RequestMapping("/register")
    public Result.RegisterResult<Integer> register(
            @RequestBody Customer customer,
            @RequestParam String code,
            HttpServletRequest request) {
        // 1. 基础参数校验
        if (customer.getPhone()  == null || customer.getPhone().trim().isEmpty())  {
            return Result.RegisterResult.fail(" 手机号不能为空");
        }
        if (customer.getEmail()  == null || !customer.getEmail().matches("^\\w+@\\w+\\.\\w+$"))  {
            return Result.RegisterResult.fail(" 邮箱格式不正确");
        }
        if (code == null || !code.matches("^\\d{6}$"))  {
            return Result.RegisterResult.fail(" 验证码必须为6位数字");
        }
        // 2. 验证码校验（移除type参数）
        if (!emailCodeService.verifyEmailCode(customer.getEmail(),  code)) {
            System.out.println("111verifyEmailCode(customer.getEmail(),  code)"+customer.getEmail()+"~~~"+code);
            return Result.RegisterResult.fail(" 验证码错误或已过期");
        }
        // 3. 查重验证
        Integer existCid = customerService.getCidByphone(customer.getPhone());
        if (existCid != null && existCid != 0) {
            return Result.RegisterResult.<Integer>fail("注册失败，已注册的ID号：" + existCid)
                    .data(existCid);
        }
        Integer existCid02 = customerService.getCidByemail(customer.getEmail());
        if (existCid02 != null && existCid02 != 0) {
            return Result.RegisterResult.<Integer>fail("注册失败，已注册的ID号：" + existCid02)
                    .data(existCid02);
        }

        // 4. 执行注册
        try {
            customer.setIp(IpUtils.getIp(request));
            customer.setRegister_date(new  Date());

            boolean success = customerService.insert(customer);
            if (success) {
                customer.setCid(customerService.getCidByphone(customer.getPhone()));
                return Result.RegisterResult.success(customer.getCid())
                        .message("注册成功");
            }
            return Result.RegisterResult.fail(" 系统繁忙，注册失败");
        } catch (Exception e) {
            return Result.RegisterResult.fail(" 注册异常：" + e.getMessage());
        }
    }





    /**
     * 基于游标的通用过滤查询
     */
    @RequestMapping("/list/filters")
    @E_UserLoginToken
    public Result<PageResult<Customer,Integer>> getCustomerListWithFilters(
            @RequestParam(required = false) Integer cursor,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) Integer cid,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String company,
            @RequestParam(required = false) Boolean hasLicense) {
        try {
            PageResult<Customer,Integer> pageResult = customerService.findCustomerListWithFilters(
                    cursor, limit,cid, name, phone, company, hasLicense
            );
            return Result.success(pageResult, "查询成功");
        } catch (Exception e) {
            return Result.fail(500, "查询失败: " + e.getMessage());
        }
    }

//    @RequestMapping("/list/filtersandstats")
//    @E_UserLoginToken
//    public Result<PageResult<Customer, String>> getCustomerListWithFilters(
//            @RequestParam(required = false) String cursor,
//            @RequestParam(defaultValue = "10") Integer limit,
//            @RequestParam(required = false) Integer cid,
//            @RequestParam(required = false) String name,
//            @RequestParam(required = false) String phone,
//            @RequestParam(required = false) String company,
//            @RequestParam(required = false) Boolean hasLicense,
//            @RequestParam(required = false) Integer active_count,
//            @RequestParam(required = false) BigDecimal cce,
//            @RequestParam(required = false) Integer cpq,
//            @RequestParam(required = false, defaultValue = "cid") String sortField,
//            @RequestParam(required = false, defaultValue = "true") Boolean sortDesc) {
//        try {
//            PageResult<Customer, String> pageResult = customerService.findCustomerListWithFiltersandStats(
//                    cursor, limit, cid, name, phone, company,
//                    hasLicense, active_count, cce, cpq, sortField, sortDesc
//            );
//            return Result.success(pageResult,  "查询成功");
//        } catch (Exception e) {
//            return Result.fail(500,  "查询失败: " + e.getMessage());
//        }
//    }

    @RequestMapping("/list/cfilters")
    @C_UserLoginToken
    public Result<PageResult<Customer,Integer>> getCustomerListWithcFilters(
            @RequestParam(required = false) Integer cursor,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) Integer cid,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String company,
            @RequestParam(required = false) Boolean hasLicense) {
        try {
            PageResult<Customer,Integer> pageResult = customerService.findCustomerListWithFilters(
                    cursor, limit,cid, name, phone, company, hasLicense
            );
            return Result.success(pageResult, "查询成功");
        } catch (Exception e) {
            return Result.fail(500, "查询失败: " + e.getMessage());
        }
    }


//    ???????????????????

    @RequestMapping("/update")
    @C_UserLoginToken
    public Result<List<Customer>> updateCustomer(@RequestBody Customer customer) {
        try {
            customerService.updateCustomer(customer);
            List<Customer> customers = customerService.findCustomerList();
            return Result.success(customers,  "更新成功");
        } catch (Exception e) {
            return Result.fail(500,  "更新失败: " + e.getMessage());
        }
    }



    @GetMapping("/stats")
    @E_UserLoginToken
    public Result<PageResult<CustomerMapper.CustomerStats, Long>> getCustomerStats(
            @RequestParam(required = false) Long cursor,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "next") String direction) {

        PageResult<CustomerMapper.CustomerStats, Long> result = customerService.getCustomerStats(
                cursor,
                limit,
                "next".equalsIgnoreCase(direction)
        );

        return Result.success(result,  "查询成功"); // 使用两个参数的success方法
    }



}
